/**
 * The program provides a sample for Java Engine functions. It creates a matrix and squares the values greater than 5.
 * Copyright 2016-2017 The MathWorks, Inc.
 */

import com.mathworks.engine.MatlabEngine;

// import  com.mathworks.engine.*;
// import java.text.DecimalFormat;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class MatlabConsole {
    public static void main(String args[]) {
        try {
            String command = "main";
            if(args.length > 0) {
                command = args[0];
            }

            Future<String[]> eFuture = MatlabEngine.findMatlabAsync();
            String[] engines = eFuture.get();
            Future<MatlabEngine> eng;
            if(engines.length > 0){
            	eng = MatlabEngine.connectMatlabAsync(engines[0]);
            }
            else {
                //Start MATLAB asynchronously
                eng = MatlabEngine.startMatlabAsync();
            }

        	// Work on other thread
			// Get engine instance from the future result
        	MatlabEngine ml = eng.get();
        	// Execute command on shared MATLAB session
        	Future<Void> vFuture = ml.evalAsync(command);
            System.out.println("Running " + command);
        	ml.close();
            // Disconnect from the MATLAB session
        	// ml.disconnect();
        } catch (ExecutionException | InterruptedException e) {
        	e.printStackTrace();
        }
    }
}
